import React, { useState, useEffect } from 'react';
import { getParkingSpots } from '../services/api';

const ParkingSpots = () => {
  const [spots, setSpots] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 首次加载数据
    const fetchSpots = async () => {
      try {
        if (loading) {
          setLoading(true);
        }
        const response = await getParkingSpots();
        setSpots(response.data);
        setError(null);
      } catch (err) {
        console.error('获取车位信息失败:', err);
        setError('获取车位信息失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchSpots();
    
    // 设置车位状态和计费的实时刷新（重要数据）
    const importantDataIntervalId = setInterval(async () => {
      try {
        const response = await getParkingSpots();
        // 只更新车位数据，不触发loading状态
        setSpots(prevSpots => {
          // 在此处可以添加数据比较逻辑，避免不必要的重渲染
          return response.data;
        });
      } catch (err) {
        console.error('更新车位信息失败:', err);
        // 静默失败，不展示错误信息
      }
    }, 1000); // 每1秒刷新一次
    
    return () => clearInterval(importantDataIntervalId);
  }, []);

  // 格式化时间为小时和分钟
  const formatDuration = (milliseconds) => {
    if (!milliseconds) return '0分钟';
    
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟`;
    } else {
      return `${minutes}分钟`;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">车位管理</h1>
      </div>
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {spots.map((spot) => (
            <div 
              key={spot.id} 
              className={`border rounded-lg p-4 ${
                spot.status === 'occupied' ? 'border-red-500 bg-red-50' : 'border-green-500 bg-green-50'
              }`}
            >
              <div className="flex justify-between items-center mb-2">
                <h3 className="text-lg font-semibold">{spot.spot_number}</h3>
                <span 
                  className={`px-2 py-1 text-xs font-semibold rounded-full ${
                    spot.status === 'occupied' ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'
                  }`}
                >
                  {spot.status === 'occupied' ? '已占用' : '空闲'}
                </span>
              </div>
              
              <div className="text-sm text-gray-600">
                {spot.status === 'occupied' && spot.plate_number && (
                  <>
                    <p className="font-medium text-red-600">
                      车牌号: <span className="font-bold">{spot.plate_number}</span>
                    </p>
                    <p>
                      <span className="font-medium">停车时长: </span>
                      {formatDuration(spot.parking_duration)}
                    </p>
                    <p>
                      <span className="font-medium">当前费用: </span>
                      <span className="font-bold text-red-600">{spot.current_fee.toFixed(2)} 元</span>
                    </p>
                    <p>
                      <span className="font-medium">入场时间: </span>
                      {spot.entry_time ? new Date(spot.entry_time).toLocaleString() : '未知'}
                    </p>
                  </>
                )}
                <p>
                  <span className="font-medium">传感器状态: </span>
                  <span className={spot.is_occupied ? 'text-red-600' : 'text-green-600'}>
                    {spot.is_occupied ? '占用' : '空闲'}
                  </span>
                </p>
                <p>
                  <span className="font-medium">最后更新: </span>
                  {new Date(spot.last_updated).toLocaleString()}
                </p>
              </div>
            </div>
          ))}
        </div>
        
        {spots.length === 0 && (
          <p className="text-gray-500 text-center py-4">暂无车位信息</p>
        )}
      </div>
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4">车位状态说明</h2>
        <div className="space-y-2">
          <div className="flex items-center">
            <div className="w-4 h-4 rounded-full bg-green-500 mr-2"></div>
            <p>空闲 - 车位当前无车辆占用</p>
          </div>
          <div className="flex items-center">
            <div className="w-4 h-4 rounded-full bg-red-500 mr-2"></div>
            <p>占用 - 车位当前有车辆占用</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ParkingSpots; 